package com.kalvan.admin.system.controller;


import com.github.pagehelper.Page;
import com.kalvan.admin.system.service.AdminService;
import com.kalvan.commons.constant.LogGroup;
import com.kalvan.commons.db.system.mapper.RoleMapper;
import com.kalvan.commons.db.system.model.Admin;
import com.kalvan.commons.db.system.model.Role;
import com.kalvan.commons.dto.system.AdminImport;
import com.kalvan.core.exception.BizException;
import com.kalvan.core.mybatis.PageInfo;
import com.kalvan.core.utils.BeanUtils;
import com.kalvan.core.utils.Sysdate;
import com.kalvan.core.valid.Add;
import com.kalvan.core.valid.Edit;
import com.kalvan.web.controller.BaseController;
import com.kalvan.web.excel.ExcelUtil;
import com.kalvan.web.exception.AdminReturnCode;
import com.kalvan.web.i18n.annotation.I18n;
import com.kalvan.web.log.LogType;
import com.kalvan.web.log.annotation.SysLog;
import com.kalvan.web.servlet.annotation.Permission;
import com.kalvan.web.servlet.response.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 管理员Controller
 *
 * @author kalvan
 * @date 2019-06-01 02:29:27
 */
@I18n("i18n/com/kalvan/admin/system/admin" )
@SysLog(group = LogGroup.ADMIN)
@Api(tags = {"管理员"})
@ApiIgnore
@RestController
@RequestMapping("system/admin" )
@Slf4j
public class AdminController extends BaseController {
    @Resource
    private AdminService adminService;
    @Resource
    private RoleMapper roleMapper;

    /**
     * 分页查询
     *
     * @param params 查询参数
     * @return R
     */
    @ApiOperation("分页查询" )
    @PostMapping("list" )
    @Permission("admin:system:admin:list" )
    public R list(PageInfo pageInfo, @RequestParam Map<String, String> params) {
        Page<Admin> data = adminService.queryPage(pageInfo, params);
        for (Admin admin : data) {
            List<Role> roles = roleMapper.selectRoleListByAdminId(admin.getId());
            admin.setRoles(roles);
        }
        return R.ok().putPage(data);
    }

    /**
     * 汇总查询 TODO
     *
     * @param params 查询参数
     * @return R
     */
    @ApiOperation("汇总查询" )
    @PostMapping("sum" )
    @Permission("admin:system:admin:sum" )
    public R sum(@RequestParam Map<String, String> params) {
        return R.ok().putData(null);
    }

    /**
     * 根据主键查询详情
     *
     * @param id 主键
     * @return R
     */
    @ApiOperation("主键查询" )
    @GetMapping("info/{id}" )
    @Permission("admin:system:admin:info" )
    public R info(@PathVariable("id" ) Long id) {
        Admin admin = adminService.findById(id);
        if (admin == null) {
            throw new BizException(AdminReturnCode.REQUEST_ILLEGAL);
        }
        List<Role> roles = roleMapper.selectRoleListByAdminId(admin.getId());
        admin.setRoles(roles);
        admin.setRoleId(roles.stream().map(Role::getId).toArray(Long[]::new));
        return R.ok().putData(admin);
    }

    private static final int DOWNLOAD_MAX_COUNT = 20000;

    /**
     * 下载
     *
     * @param params 查询参数
     */
    @ApiOperation("下载管理员" )
    @PostMapping("download" )
    @Permission("admin:system:admin:download" )
    public void download(@RequestParam Map<String, String> params, HttpServletResponse response) throws Exception {
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPage(1);
        pageInfo.setLimit(DOWNLOAD_MAX_COUNT);
        Page data = adminService.queryPage(pageInfo, params);
        String filename = "管理员" ;
        if (data.getTotal() > DOWNLOAD_MAX_COUNT) {
            throw new BizException(AdminReturnCode.PARAM_REGION_OVER.formatDesc("下载条数", "20000" ));
        }
        filename = filename + Sysdate.getTimeStr(true);
        ExcelUtil.download(filename, response, Admin.class, data);
    }

    /**
     * 新增管理员
     *
     * @param adminImport adminImport
     * @return R
     */
    @SysLog(remark = "新增管理员", type = LogType.ADD)
    @ApiOperation("新增管理员" )
    @PostMapping("add" )
    @Permission("admin:system:admin:add" )
    public R add(@Validated({Add.class}) AdminImport adminImport) {
        adminService.add(BeanUtils.newAndCopy(adminImport, Admin.class));
        return R.ok();
    }

    /**
     * 管理员导入模板下载
     *
     * @param response 流
     */
    @ApiOperation("管理员导入模板下载" )
    @GetMapping("downloadTemplate" )
    @Permission("admin:system:admin:upload" )
    public void downloadTemplate(HttpServletResponse response) throws Exception {
        ExcelUtil.downloadTemplate(templateRootPath + "com/kalvan/admin/管理员-模板.xls", response);
    }

    /**
     * 导入管理员
     *
     * @param file 上传文件
     * @return R
     */
    @SysLog(remark = "导入管理员", type = LogType.IMPORT)
    @ApiOperation("导入管理员" )
    @PostMapping("upload" )
    @Permission("admin:system:admin:upload" )
    public R upload(@RequestParam MultipartFile file) throws Exception {
        List<AdminImport> importList = ExcelUtil.importExcel(file, 1, 1, AdminImport.class);
        for (AdminImport adminImport : importList) {
            adminService.add(BeanUtils.newAndCopy(adminImport, Admin.class));
        }
        return R.ok(String.format("成功导入%s行数据", importList.size()));
    }

    /**
     * 修改管理员
     *
     * @param adminImport adminImport
     * @return R
     */
    @SysLog(remark = "修改管理员", type = LogType.EDIT)
    @ApiOperation("修改管理员" )
    @PostMapping("edit" )
    @Permission("admin:system:admin:edit" )
    public R edit(@Validated({Edit.class}) AdminImport adminImport) {
        if (adminImport.getId() == null) {
            return R.error(AdminReturnCode.REQUEST_ILLEGAL.getMsg());
        }
        adminService.edit(BeanUtils.newAndCopy(adminImport, Admin.class));
        return R.ok();
    }

    /**
     * 根据主键删除管理员
     *
     * @param ids ids
     * @return R
     */
    @SysLog(remark = "删除管理员", type = LogType.DELETE)
    @ApiOperation("删除管理员" )
    @PostMapping("delete" )
    @Permission("admin:system:admin:delete" )
    public R delete(Long[] ids) {
        if (ArrayUtils.isEmpty(ids)) {
            return R.error(AdminReturnCode.REQUEST_ILLEGAL.getMsg());
        }
        int num = adminService.deleteBatch(ids);
        return R.ok(String.format("成功删除%s行数据", num));
    }

}
